<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="tong.li&#39;s blog">
  <meta name="keyword" content="彤哥哥博客，95后技术爱好者,现就职于同程旅行/同程艺龙上海分公司，专注于互联网技术分享的平台。">
  
    <link rel="shortcut icon" href="/css/images/icon.png">
  
  <title>
    
      变量作用域与解构赋值 | 彤哥哥的博客
    
  </title>
  <link href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="https://cdn.staticfile.org/highlight.js/9.12.0/styles/tomorrow-night.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
  <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdn.staticfile.org/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdn.staticfile.org/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


  
  
    
<script src="/js/local-search.js"></script>


<meta name="generator" content="Hexo 5.4.2"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>
  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>彤哥哥的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/series/" class="item-link">分类</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/project/" class="item-link">项目</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于</a>
          
        </li>
      
      
        <li class="menu-item menu-item-search right-list">
    <a role="button" class="popup-trigger">
        <i class="fa fa-search fa-fw"></i>
    </a>
</li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/series/" class="menu-link">分类</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/project/" class="menu-link">项目</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于</a>
            
          </li>
        
      </ul>
    </div>
    
      <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
            <span class="search-icon">
                <i class="fa fa-search"></i>
            </span>
            <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off"
                    placeholder="Please enter your keyword(s) to search." spellcheck="false"
                    type="search" class="search-input">
            </div>
            <span class="popup-btn-close">
                <i class="fa fa-times-circle"></i>
            </span>
        </div>
        <div id="search-result">
            <div id="no-result">
                <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
            </div>
        </div>
    </div>
</div>
    
  </div>
</header>

    <div id="article-banner">
  <h2>变量作用域与解构赋值</h2>
  <p class="post-date">2017-12-13</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h2 id="变量作用域"><a href="#变量作用域" class="headerlink" title="变量作用域"></a>变量作用域</h2><p>在JavaScript中，用var申明的变量实际上是有作用域的。<br>如果一个变量在函数体内部申明，则该变量的作用域为整个函数体，在函数体外不可引用该变量:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var x = 1;</span><br><span class="line">    x = x + 1;</span><br><span class="line">&#125;</span><br><span class="line">x = x + 2; // ReferenceError! 无法在函数体外引用变量x</span><br></pre></td></tr></table></figure>

<p>如果两个不同的函数各自申明了同一个变量，那么该变量只在各自的函数体内起作用。换句话说，不同函数内部的同名变量互相独立，互不影响:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var x = 1;</span><br><span class="line">    x = x + 1;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function bar() &#123;</span><br><span class="line">    var x = &#x27;A&#x27;;</span><br><span class="line">    x = x + &#x27;B&#x27;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于JavaScript的函数可以嵌套，此时，内部函数可以访问外部函数定义的变量，反过来则不行:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var x = 1;</span><br><span class="line">    function bar() &#123;</span><br><span class="line">        var y = x + 1; // bar可以访问foo的变量x!</span><br><span class="line">    &#125;</span><br><span class="line">    var z = y + 1; // ReferenceError! foo不可以访问bar的变量y!</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果内部函数和外部函数的变量名重名怎么办？来测试一下:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var x = 1;</span><br><span class="line">    function bar() &#123;</span><br><span class="line">        var x = &#x27;A&#x27;;</span><br><span class="line">        console.log(&#x27;x in bar() = &#x27; + x); // &#x27;A&#x27;</span><br><span class="line">    &#125;</span><br><span class="line">    console.log(&#x27;x in foo() = &#x27; + x); // 1</span><br><span class="line">    bar();</span><br><span class="line">&#125;</span><br><span class="line">foo();</span><br></pre></td></tr></table></figure>
<p>这说明JavaScript的函数在查找变量时从自身函数定义开始，从“内”向“外”查找。如果内部函数定义了与外部函数重名的变量，则内部函数的变量将“屏蔽”外部函数的变量。</p>
<h2 id="变量提升"><a href="#变量提升" class="headerlink" title="变量提升"></a>变量提升</h2><p>JavaScript的函数定义有个特点，它会先扫描整个函数体的语句，把所有申明的变量“提升”到函数顶部:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#x27;use strict&#x27;;</span><br><span class="line">function foo() &#123;</span><br><span class="line">    var x = &#x27;Hello, &#x27; + y;</span><br><span class="line">    console.log(x);</span><br><span class="line">    var y = &#x27;Bob&#x27;;</span><br><span class="line">&#125;</span><br><span class="line">foo();</span><br></pre></td></tr></table></figure>
<p>虽然是strict模式，但语句var x = ‘Hello, ‘ + y;并不报错，原因是变量y在稍后申明了。但是console.log显示Hello, undefined，说明变量y的值为undefined。这正是因为JavaScript引擎自动提升了变量y的声明，但不会提升变量y的赋值。<br>对于上述foo()函数，JavaScript引擎看到的代码相当于:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var y; // 提升变量y的申明，此时y为undefined</span><br><span class="line">    var x = &#x27;Hello, &#x27; + y;</span><br><span class="line">    console.log(x);</span><br><span class="line">    y = &#x27;Bob&#x27;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于JavaScript的这一怪异的“特性”，我们在函数内部定义变量时，请严格遵守“在函数内部首先申明所有变量”这一规则。最常见的做法是用一个var申明函数内部用到的所有变量：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var</span><br><span class="line">        x = 1, // x初始化为1</span><br><span class="line">        y = x + 1, // y初始化为2</span><br><span class="line">        z, i; // z和i为undefined</span><br><span class="line">    // 其他语句:</span><br><span class="line">    for (i=0; i&lt;100; i++) &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="全局作用域"><a href="#全局作用域" class="headerlink" title="全局作用域"></a>全局作用域</h2><p>不在任何函数内定义的变量就具有全局作用域。实际上，JavaScript默认有一个全局对象window，全局作用域的变量实际上被绑定到window的一个属性:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x27;use strict&#x27;;</span><br><span class="line">var course = &#x27;Learn JavaScript&#x27;;</span><br><span class="line">alert(course); // &#x27;Learn JavaScript&#x27;</span><br><span class="line">alert(window.course); // &#x27;Learn JavaScript&#x27;</span><br></pre></td></tr></table></figure>
<p>因此，直接访问全局变量course和访问window.course是完全一样的。<br>你可能猜到了，由于函数定义有两种方式，以变量方式var foo = function () {}定义的函数实际上也是一个全局变量，因此，顶层函数的定义也被视为一个全局变量，并绑定到window对象:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#x27;use strict&#x27;;</span><br><span class="line">function foo() &#123;</span><br><span class="line">    alert(&#x27;foo&#x27;);</span><br><span class="line">&#125;</span><br><span class="line">foo(); // 直接调用foo()</span><br><span class="line">window.foo(); // 通过window.foo()调用</span><br></pre></td></tr></table></figure>
<p>进一步大胆地猜测，我们每次直接调用的alert()函数其实也是window的一个变量：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#x27;use strict&#x27;;</span><br><span class="line">window.alert(&#x27;调用window.alert()&#x27;);</span><br><span class="line">// 把alert保存到另一个变量:</span><br><span class="line">var old_alert = window.alert;</span><br><span class="line">// 给alert赋一个新函数:</span><br><span class="line">window.alert = function () &#123;&#125;</span><br><span class="line">alert(&#x27;无法用alert()显示了!&#x27;);</span><br><span class="line">// 恢复alert:</span><br><span class="line">window.alert = old_alert;</span><br><span class="line">alert(&#x27;又可以用alert()了!&#x27;);</span><br></pre></td></tr></table></figure>
<p>这说明JavaScript实际上只有一个全局作用域。任何变量（函数也视为变量），如果没有在当前函数作用域中找到，就会继续往上查找，最后如果在全局作用域中也没有找到，则报ReferenceError错误.</p>
<h2 id="名称空间"><a href="#名称空间" class="headerlink" title="名称空间"></a>名称空间</h2><p>全局变量会绑定到window上，不同的JavaScript文件如果使用了相同的全局变量，或者定义了相同名字的顶层函数，都会造成命名冲突，并且很难被发现。<br>减少冲突的一个方法是把自己的所有变量和函数全部绑定到一个全局变量中。例如:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">// 唯一的全局变量MYAPP:</span><br><span class="line">var MYAPP = &#123;&#125;;</span><br><span class="line">// 其他变量:</span><br><span class="line">MYAPP.name = &#x27;myapp&#x27;;</span><br><span class="line">MYAPP.version = 1.0;</span><br><span class="line">// 其他函数:</span><br><span class="line">MYAPP.foo = function () &#123;</span><br><span class="line">    return &#x27;foo&#x27;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>把自己的代码全部放入唯一的名字空间MYAPP中，会大大减少全局变量冲突的可能。<br>许多著名的JavaScript库都是这么干的：jQuery，YUI，underscore等等。</p>
<h2 id="局部作用域"><a href="#局部作用域" class="headerlink" title="局部作用域"></a>局部作用域</h2><p>由于JavaScript的变量作用域实际上是函数内部，我们在for循环等语句块中是无法定义具有局部作用域的变量的:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#x27;use strict&#x27;;</span><br><span class="line"></span><br><span class="line">function foo() &#123;</span><br><span class="line">    for (var i=0; i&lt;100; i++) &#123;</span><br><span class="line">        //</span><br><span class="line">    &#125;</span><br><span class="line">    i += 100; // 仍然可以引用变量i</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>为了解决块级作用域，ES6引入了新的关键字let，用let替代var可以申明一个块级作用域的变量:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">    var sum = 0;</span><br><span class="line">    for (let i=0; i&lt;100; i++) &#123;</span><br><span class="line">        sum += i;</span><br><span class="line">    &#125;</span><br><span class="line">    // SyntaxError:</span><br><span class="line">    i += 1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="常量"><a href="#常量" class="headerlink" title="常量"></a>常量</h2><p>由于var和let申明的是变量，如果要申明一个常量，在ES6之前是不行的，我们通常用全部大写的变量来表示“这是一个常量，不要修改它的值”:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var PI = 3.14;</span><br></pre></td></tr></table></figure>
<p>ES6标准引入了新的关键字const来定义常量，const与let都具有块级作用域:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x27;use strict&#x27;;</span><br><span class="line">const PI = 3.14;</span><br><span class="line">PI = 3; // 某些浏览器不报错，但是无效果！</span><br><span class="line">PI; // 3.14</span><br></pre></td></tr></table></figure>
<h2 id="解构赋值"><a href="#解构赋值" class="headerlink" title="解构赋值"></a>解构赋值</h2><p>从ES6开始，JavaScript引入了解构赋值，可以同时对一组变量进行赋值。<br>什么是解构赋值？我们先看看传统的做法，如何把一个数组的元素分别赋值给几个变量:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var array = [&#x27;李彤&#x27;, &#x27;奕明创意传媒&#x27;, &#x27;艺术源于生活,但高于生活&#x27;];</span><br><span class="line">//一般赋值方法</span><br><span class="line">var x = array[0];</span><br><span class="line">var y = array[1];</span><br><span class="line">var z = array[2];</span><br><span class="line">console.log(&#x27;x : &#x27; + x + &#x27;, y : &#x27; + y + &#x27;, z : &#x27; + z);  //x : 李彤, y : 奕明创意传媒, z : 艺术源于生活,但高于生活</span><br></pre></td></tr></table></figure>
<p>现在，在ES6中，可以使用解构赋值，直接对多个变量同时赋值:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var [x, y, z] = [&#x27;Java&#x27;, &#x27;JavaScript&#x27;, &#x27;Python&#x27;];</span><br><span class="line">console.log(&#x27;x : &#x27; + x + &#x27;, y : &#x27; + y + &#x27;, z : &#x27; + z); //x : Java, y : JavaScript, z : Python</span><br></pre></td></tr></table></figure>
<p>注意，对数组元素进行解构赋值时，多个变量要用[…]括起来。<br>如果数组本身还有嵌套，也可以通过下面的形式进行解构赋值，注意嵌套层次和位置要保持一致:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">let [x, [y, z]] = [&#x27;hello&#x27;, [&#x27;JavaScript&#x27;, &#x27;ES6&#x27;]];</span><br><span class="line">x; // &#x27;hello&#x27;</span><br><span class="line">y; // &#x27;JavaScript&#x27;</span><br><span class="line">z; // &#x27;ES6&#x27;</span><br></pre></td></tr></table></figure>
<p>解构赋值还可以忽略某些元素：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">let [, , z] = [&#x27;hello&#x27;, &#x27;JavaScript&#x27;, &#x27;ES6&#x27;]; // 忽略前两个元素，只对z赋值第三个元素</span><br><span class="line">z; // &#x27;ES6&#x27;</span><br></pre></td></tr></table></figure>
<p>如果需要从一个对象中取出若干属性，也可以使用解构赋值，便于快速获取对象的指定属性:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">var person = &#123;</span><br><span class="line">    name: &#x27;旺财&#x27;,</span><br><span class="line">    age: 20,</span><br><span class="line">    gender: &#x27;male&#x27;,</span><br><span class="line">    passport: &#x27;G-12345678&#x27;,</span><br><span class="line">    school: &#x27;No.4 middle school&#x27;</span><br><span class="line">&#125;;</span><br><span class="line">var &#123;name, age, passport&#125; = person;</span><br><span class="line">// name, age, passport分别被赋值为对应属性:</span><br><span class="line">console.log(&#x27;name = &#x27; + name + &#x27;, age = &#x27; + age + &#x27;, passport = &#x27; + passport);  //name = 旺财, age = 20, passport = G-12345678</span><br></pre></td></tr></table></figure>
<p>对一个对象进行解构赋值时，同样可以直接对嵌套的对象属性进行赋值，只要保证对应的层次是一致的:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">var person = &#123;</span><br><span class="line">    name: &#x27;小强&#x27;,</span><br><span class="line">    age: 20,</span><br><span class="line">    gender: &#x27;male&#x27;,</span><br><span class="line">    passport: &#x27;G-12345678&#x27;,</span><br><span class="line">    school: &#x27;No.4 middle school&#x27;,</span><br><span class="line">    address: &#123;</span><br><span class="line">        city: &#x27;Beijing&#x27;,</span><br><span class="line">        street: &#x27;No.1 Road&#x27;,</span><br><span class="line">        zipcode: &#x27;100001&#x27;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">var &#123;name, address: &#123;city, zip&#125;&#125; = person;</span><br><span class="line">name; // &#x27;小强&#x27;</span><br><span class="line">city; // &#x27;Beijing&#x27;</span><br><span class="line">zip; // undefined, 因为属性名是zipcode而不是zip</span><br><span class="line">// 注意: address不是变量，而是为了让city和zip获得嵌套的address对象的属性:</span><br><span class="line">address; // Uncaught ReferenceError: address is not defined</span><br></pre></td></tr></table></figure>
<p>使用解构赋值对对象属性进行赋值时，如果对应的属性不存在，变量将被赋值为undefined，这和引用一个不存在的属性获得undefined是一致的。如果要使用的变量名和属性名不一致，可以用下面的语法获取:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var person = &#123;</span><br><span class="line">    name: &#x27;小强&#x27;,</span><br><span class="line">    age: 20,</span><br><span class="line">    gender: &#x27;male&#x27;,</span><br><span class="line">    passport: &#x27;G-12345678&#x27;,</span><br><span class="line">    school: &#x27;No.4 middle school&#x27;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">// 把passport属性赋值给变量id:</span><br><span class="line">let &#123;name, passport:id&#125; = person;</span><br><span class="line">name; // &#x27;小强&#x27;</span><br><span class="line">id; // &#x27;G-12345678&#x27;</span><br><span class="line">// 注意: passport不是变量，而是为了让变量id获得passport属性:</span><br><span class="line">passport; // Uncaught ReferenceError: passport is not defined</span><br></pre></td></tr></table></figure>
<p>解构赋值还可以使用默认值，这样就避免了不存在的属性返回undefined的问题:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var person = &#123;</span><br><span class="line">    name: &#x27;小强&#x27;,</span><br><span class="line">    age: 20,</span><br><span class="line">    gender: &#x27;male&#x27;,</span><br><span class="line">    passport: &#x27;G-12345678&#x27;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">// 如果person对象没有single属性，默认赋值为true:</span><br><span class="line">var &#123;name, single=true&#125; = person;</span><br><span class="line">name; // &#x27;小强&#x27;</span><br><span class="line">single; // true</span><br></pre></td></tr></table></figure>
<p>有些时候，如果变量已经被声明了，再次赋值的时候，正确的写法也会报语法错误:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// 声明变量:</span><br><span class="line">var x, y;</span><br><span class="line">// 解构赋值:</span><br><span class="line">&#123;x, y&#125; = &#123; name: &#x27;小强&#x27;, x: 100, y: 200&#125;;</span><br><span class="line">// 语法错误: Uncaught SyntaxError: Unexpected token =</span><br></pre></td></tr></table></figure>
<p>这是因为JavaScript引擎把{开头的语句当作了块处理，于是=不再合法。解决方法是用小括号括起来:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(&#123;x, y&#125; = &#123; name: &#x27;小强&#x27;, x: 100, y: 200&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="解析赋值使用场景"><a href="#解析赋值使用场景" class="headerlink" title="解析赋值使用场景"></a>解析赋值使用场景</h2><ul>
<li>解构赋值在很多时候可以大大简化代码。例如，交换两个变量x和y的值，可以这么写，不再需要临时变量:  <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var x=1, y=2;</span><br><span class="line">[x, y] = [y, x]</span><br></pre></td></tr></table></figure></li>
<li>快速获取当前页面的域名和路径:  <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var &#123;hostname:domain, pathname:path&#125; = location;</span><br><span class="line">domain //&quot;ltyeamin.github.io&quot;</span><br><span class="line">path // &quot;/2017/12/04/JS%E5%87%BD%E6%95%B0%E5%AE%9A%E4%B9%89%E5%92%8C%E8%B0%83%E7%94%A8/&quot;</span><br></pre></td></tr></table></figure></li>
<li>如果一个函数接收一个对象作为参数，那么，可以使用解构直接把对象的属性绑定到变量中。例如，下面的函数可以快速创建一个Date对象:  <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function buildDate(&#123;year, month, day, hour=0, minute=0, second=0&#125;) &#123;</span><br><span class="line">    return new Date(year + &#x27;-&#x27; + month + &#x27;-&#x27; + day + &#x27; &#x27; + hour + &#x27;:&#x27; + minute + &#x27;:&#x27; + second);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
  它的方便之处在于传入的对象只需要year、month和day这三个属性:  <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">buildDate(&#123; year: 2017, month: 12, day: 4 &#125;); // Mon Dec 04 2017 00:00:00 GMT+0800 (中国标准时间)</span><br></pre></td></tr></table></figure>
  也可以传入hour、minute和second属性:  <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">buildDate(&#123; year: 2017, month: 1, day: 1, hour: 20, minute: 15 &#125;); // Sun Jan 01 2017 20:15:00 GMT+0800 (中国标准时间)</span><br></pre></td></tr></table></figure>
使用解构赋值可以减少代码量，但是，需要在支持ES6解构赋值特性的现代浏览器中才能正常运行。目前支持解构赋值的浏览器包括Chrome，Firefox，Edge等.</li>
</ul>
</section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#JavaScript" >
    <span class="tag-code">JavaScript</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2017/12/04/JS%E5%87%BD%E6%95%B0%E5%AE%9A%E4%B9%89%E5%92%8C%E8%B0%83%E7%94%A8/">
        <span class="nav-arrow">← </span>
        
          JS函数定义和调用
        
      </a>
    
    
      <a class="nav-right" href="/2017/12/13/JS%E6%96%B9%E6%B3%95/">
        
          JS方法
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">若你觉得我的文章对你有帮助，欢迎点击上方按钮对我打赏</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Utterances START -->
      <div id="utterances"></div>
      <script src="https://utteranc.es/client.js"
        repo="ltyeamin/blogtalks"
        issue-term="pathname"
        theme="github-light"
        crossorigin="anonymous"
        async></script>    
      <!-- Utterances END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%8F%98%E9%87%8F%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-nav-text">变量作用域</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%8F%98%E9%87%8F%E6%8F%90%E5%8D%87"><span class="toc-nav-text">变量提升</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%85%A8%E5%B1%80%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-nav-text">全局作用域</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%90%8D%E7%A7%B0%E7%A9%BA%E9%97%B4"><span class="toc-nav-text">名称空间</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%B1%80%E9%83%A8%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="toc-nav-text">局部作用域</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%B8%B8%E9%87%8F"><span class="toc-nav-text">常量</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E8%A7%A3%E6%9E%84%E8%B5%8B%E5%80%BC"><span class="toc-nav-text">解构赋值</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E8%A7%A3%E6%9E%90%E8%B5%8B%E5%80%BC%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-nav-text">解析赋值使用场景</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://example.com/2017/12/13/变量作用域与解构赋值/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', '/css/images/error_icon.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== '/css/images/error_icon.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>






    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2024 | Proudly powered by <a href="https://hexo.io" target="_blank">Hexo</a>
    <br>
    Theme by <a target="_blank" rel="noopener" href="https://github.com/ltyeamin">tong.li</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("https://cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("https://cdn.staticfile.org/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      hljs.configure({useBR: true});
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->



<script src='https://cdn.staticfile.org/mermaid/8.11.2/mermaid.min.js'></script>



<script src="/js/script.js"></script>


  </body>
</html>